package com.usian.admin.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.gson.JsonArray;
import com.usian.admin.feign.ArticleFeign;
import com.usian.admin.feign.WmNewsFeign;
import com.usian.admin.mapper.AdSensitiveMapper;
import com.usian.admin.service.AdChannelService;
import com.usian.admin.service.AdSensitiveService;
import com.usian.admin.service.WemediaNewsAutoScanService;
import com.usian.common.aliyun.GreenImageScan;
import com.usian.common.aliyun.GreenTextScan;
import com.usian.common.fsdfs.FastDFSClientUtil;
import com.usian.model.admin.pojos.AdChannel;
import com.usian.model.article.pojos.ApArticle;
import com.usian.model.article.pojos.ApArticleConfig;
import com.usian.model.article.pojos.ApArticleContent;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.common.SensitiveWordUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Log4j2
@Service
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {

    @Autowired
    private WmNewsFeign wmNewsFeign;

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private FastDFSClientUtil fastDFSClientUtil;

    @Autowired
    private AdSensitiveService adSensitiveService;

    @Autowired
    private AdChannelService adChannelService;

    @Value("${fileServerUrl}")
    private String imageUrl;

    /**
     * 文章审核
     * @param id
     */
    @Override
    public void NewsAutoScan(Integer id) {
        try {
            //1:校验参数
            if(id ==null){
                log.info("审核文章id为空");
                return;
            }

            //2：查找文章信息
            WmNews wmNews = wmNewsFeign.findById(id);
            if (wmNews == null) {
                log.error("审核的自媒体文章不存在，自媒体的id:{}", id);
                return;
            }

            //3:判断状态 人工审核 3  待发布8 已发布9   staus   1     4 人工审核通过
            if(wmNews.getStatus()==4){
                //人工审核通过
                this.saveArticle(wmNews);
                return;
            }

            if(wmNews.getStatus()==8 && wmNews.getPublishTime().getTime()<=System.currentTimeMillis()){
                //待发布--》已发布
                this.saveArticle(wmNews);
                return;
            }

            if(wmNews.getStatus()==1){
                //3:调用阿里云和敏感词
                //待审核
                Map<String, Object> handle = this.handleTextAndImages(wmNews);
                //1:审文本
                Map map = greenTextScan.greenTextScan(handle.get("content").toString());
                //pass 通过 block 不通过 review 不确定
                if(!map.get("suggestion").equals("pass")){

                    if (map.get("suggestion").equals("block")){
                        //修改wmnews status 为 2 审核失败
                        this.updateWmnews(wmNews,(short)2,"阿里云文本审核不通过");
                    }
                    if (map.get("suggestion").equals("review")){
                        //修改wmnews status 为 3 人工审核
                        this.updateWmnews(wmNews,(short)3,"阿里云文本审核结果不确定");
                    }
                }

                //2:审图片
                List<String> imageList = (List<String>)handle.get("image");
                List<byte[]> imageByte =new ArrayList<>();
                for(String image:imageList){
                    //group1/M00/1/3/2/XXXX.jpg
                    String imageName = image.replace(imageUrl, "");
                    int index = imageName.indexOf("/");
                    //group1
                    String groupName = imageName.substring(0, index);
                    //M00/1/3/2/XXXX.jpg
                    String url = imageName.substring(index + 1);

                    byte[] bytes = fastDFSClientUtil.download(groupName, url);
                    imageByte.add(bytes);
                }

                Map imageMap = greenImageScan.imageScan(imageByte);
                if(!imageMap.get("suggestion").equals("pass")){

                    if (imageMap.get("suggestion").equals("block")){
                        //修改wmnews status 为 2 审核失败
                        this.updateWmnews(wmNews,(short)2,"阿里云图片审核不通过");
                    }
                    if (imageMap.get("suggestion").equals("review")){
                        //修改wmnews status 为 3 人工审核
                        this.updateWmnews(wmNews,(short)3,"阿里云图片审核结果不确定");
                    }
                }

                //3:审核敏感词 DFA
                List<String> allSensitive = adSensitiveService.findAllSensitive();
                SensitiveWordUtil.initMap(allSensitive);
                Map<String, Integer> words = SensitiveWordUtil.matchWords(handle.get("content").toString());
                if(words.size()>0){
                    //大于0 不通过
                    this.updateWmnews(wmNews,(short)2,"文本敏感词审核不通过");
                }

                //如果全通过 发布时间>当前审核时间 8 待发布   发布时间<当前审核时间 9 已发布
                if(wmNews.getPublishTime().getTime()>System.currentTimeMillis()){
                    this.updateWmnews(wmNews,(short)8,"审核通过，发布时间未到");
                }
                //4:文章 维护到 3个文章表 ，跟新wmnews  status 9
                this.saveArticle(wmNews);

            }


        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void saveArticle(WmNews wmNews){
        //1:ap_article
        ApArticle apArticle = new ApArticle();
        apArticle.setTitle(wmNews.getTitle());
        apArticle.setLayout(wmNews.getType());
        apArticle.setImages(wmNews.getImages());
        apArticle.setCreatedTime(new Date());

        Integer userId = wmNews.getUserId();
        WmUser wmuser = wmNewsFeign.findWmUserById(userId.longValue());
        if(wmuser!=null){
            ApAuthor apAuthor = articleFeign.findByName(wmuser.getName());
            if(apAuthor!=null){
                apArticle.setAuthorId(apAuthor.getId().longValue());
                apArticle.setAuthorName(apAuthor.getName());
            }
        }

        Integer channelId = wmNews.getChannelId();
        AdChannel adChannel = adChannelService.getOne(Wrappers.<AdChannel>lambdaQuery().eq(AdChannel::getId, channelId));
        if(adChannel!=null){
            apArticle.setChannelId(adChannel.getId());
            apArticle.setChannelName(adChannel.getName());
        }
        articleFeign.saveApArticle(apArticle);


        //2:ap_article_content
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(wmNews.getContent());
        articleFeign.saveArticleContent(apArticleContent);

        //3:ap_article_config
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setIsDown(true);
        apArticleConfig.setIsComment(true);
        articleFeign.saveArticleConfig(apArticleConfig);

        //4:修改wmnews  status =9
        updateWmnews(wmNews,(short)9,"审核通过");

    }

    //修改文章状态
    private void updateWmnews(WmNews wmNews,Short status,String msg){
        wmNews.setStatus(status);
        wmNews.setReason(msg);
        wmNewsFeign.updateWmNews(wmNews);
    }


    //分离文章中的文本和图片
    private Map<String,Object> handleTextAndImages(WmNews wmNews){

        String content = wmNews.getContent();
        //存放文本
        StringBuilder s = new StringBuilder();
        //存放图片
        List<String> images = new ArrayList<>();

        //处理文章内容
        List<Map> contentList = JSONArray.parseArray(content, Map.class);
        for(Map map :contentList){

            if(map.get("type").equals("text")){
                s.append(map.get("value"));
            }
            if(map.get("type").equals("image")){
                images.add(map.get("value").toString());
            }
        }

        //处理文章封面
        if(wmNews.getImages()!=null){
            String[] strings = wmNews.getImages().split(",");
            //for(String s1 :strings){
            //    images.add(s1);
            //}
            images.addAll(Arrays.asList(strings));  //Arrays.asList 面试题  加进去的元素在遍历时删除会报错  内部arrayList和对象本生不是一个集合
        }

        //分离文本和图片后封装成map集合返回
        Map<String,Object> resultMap =new HashMap<>();
        resultMap.put("content",s.toString());
        resultMap.put("image",images);
        return resultMap;
    }
}
